var prefix = jsctx + "/elecStation";

var station = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    function reset() {
        $("#stationName").val('');
        $("#operatorName").val('');
        $("#bizType").val('');
        $("#stationStaus").val('');
    }

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                stationName: $("#stationName").val().trim(),
                operatorName: $("#operatorName").val().trim(),
                bizType:$("#bizType").val(),
                stationStaus:$("#stationStaus").val(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listStation",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 10,
                    pageList: [10, 20, 30],
                    pageNumber: 1,
                    sidePagination: "server",
                    paginationShowPageGo: true,
                    height: h,
                    rightFixedColumns: true,
                    rightFixedNumber: 1,
                    // showColumns: false,
                    // cache: false,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            stationName: $("#stationName").length > 0 ? $("#stationName").val().trim() : "",
                            operatorName: $("#operatorName").length > 0 ? $("#operatorName").val().trim() : "",
                            bizType:$("#bizType").val(),
                            stationStaus:$("#stationStaus").val()
                            /*operateStatus: $("#operateStatus").val().trim(),
                            areaId: $("#areaId").val().trim(),
                            stationNo: $("#stationNo").val().trim(),
                            bizType: $("#bizType").val().trim(),
                            showPlaceType: $("#showPlaceType").val().trim(),
                            tenantCompanyId: $("#tenantCompanyId").val().trim(),
                            stationType: $("#stationType").val()*/
                        };
                    },
                    columns: [
                        {field: 'stationNo', title: '站点编号', width: '80', align: 'center'},
                        {field: 'stationName', title: '站点名称', width: '100', align: 'center'},
                        {
                            field: 'bizType', title: '站点类型', width: '80', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span class="label label-success">自营</span>'
                                } else if (value == '1') {
                                    return '<span class="label label-info">加盟</span>'
                                }
                            }
                        },
                        {field: '', title: '所属区域', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                return '<span >'+row.provinceName+'省'+row.cityName+'市'+row.areaName+'</span>'
                            }},
                        {field: 'labelName', title: '标签名称', width: '100', align: 'center'},
                        {field: 'operatorName', title: '所属加盟商', width: '100', align: 'center'},
                        {field: 'operatorType', title: '加盟商类型', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span class="label label-success">加盟</span>'
                                } else if (value == '1') {
                                    return '<span class="label label-info">自营</span>'
                                }
                            }},
                        {
                            field: 'stationStaus', title: '站点状态',
                            width: '80', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span class="label label-success">停用</span>'
                                } else if (value == '1') {
                                    return '<span class="label label-info">正常</span>'
                                }
                            }
                        },
                        {field: 'quickOrSlow', title: '充电类型(快/慢)', width: '150', align: 'center'},
                        {field: 'totalPileNum', title: '充电桩数量', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                return '<a helf="javascipt:void(0)" style="color:#06F !important" onclick="station.subgo(1,\''
                                    + row.elecStationId
                                    + '\')">'+value+'</a>'
                            }},
                        {field: 'totalGunNum', title: '充电枪数量', width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                return '<a helf="javascipt:void(0)" style="color:#06F !important" onclick="station.subgo(2,\''
                                    + row.elecStationId
                                    + '\')">'+value+'</a>'
                            }},
                        {field: 'operateStartTime', title: '投运时间', width: '100', align: 'center'},
                        {field: 'stationRemark', title: '桩群备注', width: '200', align: 'left' },
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '200', align: 'center',
                            class: 'operate-td',
                            formatter: function (value, row, index) {
                                var a = '';
                                var b = '';
                                var c = '';
                                var d = '';
                                var f = '';
                                var g = '';
                                var h = '';
                                var i = '';
                                var j = '';
                                if (StationManager_station_look) {
                                    f = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="充电站详情" onclick="station.detailStation(\''
                                        + row.elecStationId
                                        + '\')">详情</a> ';
                                }
                                if (StationManager_station_update) {
                                    b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑充电站" onclick="station.editStation(\''
                                        + row.elecStationId
                                        + '\')">编辑充电站</a> ';
                                    d = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" title="收费列表" onclick="station.electricityPrice(\''
                                        + row.elecStationId
                                        + '\')">电价列表</a> ';
                                    j = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="占桩费配置" onclick="station.showModel(\''
                                        + row.elecStationId + '\',\''+ row.occupyStatus + '\',\''+ row.occupyPrice + '\',\''+ row.occupyFree + '\')">' +
                                        '占桩费配置</a> ';
                                    var c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="删除" onclick="station.deleteStation(\''
                                        + row.elecStationId
                                        + '\')">删除</a> ';
                                }
                                return b + a + f + c + d + g + h + i + j;
                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        getCountData();
    }

    function addStation() {
        location.href = prefix + "/addStation";
    }

    function subgo(_val,_id) {
        if (_val==1){
            location.href = prefix+"/elecPileSub/"+_id;
        }else{
            location.href = prefix+"/elecGunSub/"+_id;
        }
    }

    //设置电价
    function electricityPrice(elecStationId) {
        location.href = prefix + "/elecStationPrice/" + elecStationId;
    }

    function editStation(elecStationId) {
        location.href = prefix + "/editStation/" + elecStationId;
    }

    function detailStation(elecStationId) {
        location.href = prefix + "/detailStation/" + elecStationId;
    }

    //桩页面
    function pileListPage(elecStationId) {
        location.href = prefix + "/pileListPage/" + elecStationId;
    }

    function getCountData() {
        $.ajax({
            url: prefix + "/statisticsStationNum",
            type: "get",
            data: {
                stationName: $("#stationName").length > 0 ? $("#stationName").val().trim() : "",
                operatorName: $("#operatorName").length > 0 ? $("#operatorName").val().trim() : "",
                bizType:$("#bizType").val(),
                stationStaus:$("#stationStaus").val()
            },
            success: function (data) {
                if (data!=null){
                    if(data.isFlag==1){
                        $("#isFlag0").css("display","none");
                        $("#isFlag1").css("display","none");
                    }

                    $("#operatorId").text(data.operatorCount);
                    $("#stationId").text(data.stationCount);
                    $("#pileId").text(data.pileCount);
                    $("#kuaiId").text(data.kuaiNum);
                    $("#manId").text(data.manNum);
                    $("#gunId").text(data.gunCount);

                    $("#kxId").text(data.kxNum);
                    $("#cqId").text(data.cqNum);
                    $("#qdzId").text(data.qdzNum);
                    $("#cdzId").text(data.cdzNum);
                    $("#yjsId").text(data.yjsNum);
                    $("#gzId").text(data.gzNum);
                    $("#lxId").text(data.lxNum);

                }
            }
        });
    }

    function deleteStation(elecStationId) {
        layer.confirm('确定要删除选中的记录(对应的桩和枪都会被删除)？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteStation",
                type: "post",
                data: {
                    'elecStationId': elecStationId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }
    
    function statisticsStationNum() {
        $.ajax({
            url: prefix + "/statisticsStationNum",
            type: "post",
            data: {
                stationName: $("#stationName").val().trim(),
                operatorName: $("#operatorName").val().trim(),
                bizType:$("#bizType").val(),
                stationStaus:$("#stationStaus").val()
            },
            success: function (data) {
                layer.close(index);
                if (data.status == 200) {
                   // layer.msg("删除成功");
                }
            }
        });
    }


    function goBack() {
        location.href = prefix + "/index";
    }

    function changeStatus(elecStationId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'elecStationId': elecStationId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function getArea() {
        var cityId = $("#cityId").val().trim();
        if (cityId == null || cityId == '') {
            $("#area").html("");
            var str = "<option value=''>行政区域</option>";
            $("#area").append(str);
        } else {
            $.ajax({
                url: prefix + "/getArea",
                type: "GET",
                data: {
                    cityId: cityId
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    $("#areaId").html("");
                    var str = "<option value=''>--请选择--</option>";
                    if (data.status == 200) {
                        $.each(data.data, function (i, item) {
                            str += "<option value=" + item.areaId + ">" + item.areaName + "</option>";
                        })
                        $("#areaId").append(str);
                    } else {
                        // parent.layer.msg(data.message);
                        $("#areaId").val("");
                    }
                }
            });
        }

    }

    function getCity() {
        var provinceId = $("#provinceId").val().trim();
        if (provinceId == null || provinceId == '') {
            $("#city").html("");
            var str = "<option>市区</option>";
            $("#city").append(str);
        } else {
            $.ajax({
                url: prefix + "/getCity",
                type: "GET",
                data: {
                    provinceId: provinceId
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    $("#cityId").html("");
                    var str = "<option value=''>--请选择--</option>";
                    if (data.status == 200) {
                        $.each(data.data, function (i, item) {
                            str += "<option value=" + item.cityId + ">" + item.cityName + "</option>";
                        })
                        $("#cityId").append(str);
                    } else {
                        // parent.layer.msg(data.message);
                        $("#cityId").val("");
                    }
                }
            });
        }

    }

    function jumpDiscountPolicyPage(elecStationId) {
        location.href = prefix + "/jumpDiscountPolicyPage/" + elecStationId;
    };



    function elecStationOut(elecStationId) {
        location.href = prefix + "/elecStationOut/" + elecStationId;
    }

    function tenantOperatorStation(elecStationId) {
        location.href = prefix + "/tenantOperatorStation/" + elecStationId;
    }

    function showModel(id,occupyStatus,occupyPrice,occupyFree) {
        var $ = layui.jquery, form = layui.form;
        if (occupyStatus == '0') {
            $('input[name="occupyStatus"][value = "0"]').prop('checked', 'true')
        } else {
            $('input[name="occupyStatus"][value = "1"]').prop('checked', 'true')
        }

        form.render();
        $("#occupyFree").val(occupyPrice);
        if (occupyFree!='null'){
            $("#occupyPrice").val(occupyFree);
        }else{
            $("#occupyPrice").val(0);
        }

        $('#exampleModal').modal('show');

        $("#submitForm").unbind("click").bind("click", function () {
            //debugger
            $.ajax({
                url: prefix + "/updateOccupy",
                type: "post",
                data: {
                    "id": id,
                    "occupyStatus": $("input[name='occupyStatus']:checked").val(),
                    "occupyFree": $("#occupyFree").val(),
                    "occupyPrice": $("#occupyPrice").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                    }
                }
            })
        })

    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        reset: reset,
        addStation: addStation,
        pileListPage: pileListPage,
        changeStatus: changeStatus,
        deleteStation: deleteStation,
        getArea: getArea,
        getCity: getCity,
        editStation: editStation,
        electricityPrice: electricityPrice,
        detailStation: detailStation,
        jumpDiscountPolicyPage: jumpDiscountPolicyPage,
        exportList: exportList,
        elecStationOut: elecStationOut,
        tenantOperatorStation: tenantOperatorStation,
        getCountData: getCountData,
        subgo: subgo,
        showModel: showModel
    };
})();

var addElecStation = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        // var totalSize = 0;
        // $("input[type='file']").each(function () {
        //     console.log($(this))
        //     if($(this)[0].files.length==1){
        //         totalSize +=$(this)[0].files[0].size;
        //     }
        // })
        // if(totalSize>10485760){
        //     layer.msg('请确保图片大小之和小于10M');
        //     return
        // }
        var formData = new FormData($("#frmElecStation")[0]);
        //$("#roleIds").val(getCheckedRoles());
        if (isajaxsend) {
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateElecStation",
                data: formData,
                processData: false,
                contentType: false,
                // async: false,
                beforeSend: function () {
                    isajaxsend = false;
                    parent.layer.msg("图片上传中...", {time: -1});
                },
                error: function (request) {
                    isajaxsend = true
                    console.log(request)
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = false
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true
                        parent.layer.alert(data.message)
                    }

                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmElecStation").validate({
            rules: {
                stationName: {
                    required: true,
                    maxlength: 50
                },
                operatorId: {
                    required: true
                } ,
                provinceId: {
                    required: true
                } ,
                stationStaus: {
                    required: true
                }
            },
            messages: {
                stationName: {
                    required: icon + "请输入桩群名称",
                    maxlength: icon + "桩群名称最大长度为50"
                },operatorId: {
                    required: icon + "请选择所属加盟商"
                },provinceId: {
                    required: icon + "请选择省-市-区"
                },stationStaus: {
                    required: icon + "请选择站点状态"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();


var elecStationOut = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            var formData = new FormData($("#frmElecStationOut")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateElecStationOut",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmElecStationOut").validate({
            rules: {
                operatorId: {
                    required: true
                },
                labelId: {
                    required: true
                },
                outType: {
                    required: true
                },
                printerType: {
                    required: true
                },
                isFreeParking: {
                    required: true
                },
                isNeedNumber: {
                    required: true
                }
            },
            messages: {
                outType: {
                    required: icon + "请选择出场方式"
                },
                printerType: {
                    required: icon + "请选择打印机类型"
                },
                isFreeParking: {
                    required: icon + "请选择是否免费2个小时停车"
                },
                isNeedNumber: {
                    required: icon + "请选择是否必须车牌号"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();
